package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.code.BusinessBizCode;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.system.dao.SysPostDao;
import com.ruoyi.system.dao.SysUserPostDao;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.swing.text.html.Option;
import java.util.*;

/**
 * 岗位信息 服务层处理
 *
 * @author wintersnow
 * @since 1.0  2020-12-12
 */
@Transactional(readOnly = true)
@Service
public class SysPostServiceImpl implements ISysPostService {

    @Autowired
    private SysPostDao postDao;

    @Autowired
    private SysUserPostDao userPostDao;

    /**
     * 查询岗位信息集合
     *
     * @param req 岗位信息
     * @return 岗位信息集合
     */
    @Override
    public Page<SysPost> selectPostList(SysPost req) {
        Specification<SysPost> example = new Specification<SysPost>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<SysPost> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNoneBlank(req.getPostCode())) {
                    Predicate pre = cb.like(root.get("postCode").as(String.class), "%" + req.getPostCode() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getPostName())) {
                    Predicate pre = cb.like(root.get("postName").as(String.class), "%" + req.getPostName() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getStatus())) {
                    Predicate pre = cb.equal(root.get("status").as(String.class), req.getStatus());
                    list.add(pre);
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        }
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(), pageDomain.getPageSize(), Sort.Direction.ASC, Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("postSort"));
        Page<SysPost> page = postDao.findAll(example, pageable);
        return page;
    }

    /**
     * 查询所有岗位
     *
     * @return 岗位列表
     */
    @Override
    public List<SysPost> selectPostAll() {
        return postDao.findAll();
    }

    /**
     * 通过岗位ID查询岗位信息
     *
     * @param postId 岗位ID
     * @return 角色对象信息
     */
    @Override
    public SysPost selectPostById(Long postId) {
        return postDao.findById(postId).orElse(new SysPost());
    }

    /**
     * 根据用户ID获取岗位选择框列表
     *
     * @param userId 用户ID
     * @return 选中岗位ID列表
     */
    @Override
    public List<Long> selectPostListByUserId(Long userId) {
        List<Long> ids = postDao.findPostListByUserId(userId);
        return ids;
    }

    /**
     * 校验岗位名称是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostNameUnique(SysPost post) {
        Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
        List<SysPost> posts = postDao.findByPostName(post.getPostName());
        if (!posts.isEmpty() && posts.get(0).getPostId().longValue() != postId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验岗位编码是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostCodeUnique(SysPost post) {
        Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
        List<SysPost> posts = postDao.findByPostCode(post.getPostName());
        if (!posts.isEmpty() && posts.get(0).getPostId().longValue() != postId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 通过岗位ID查询岗位使用数量
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public int countUserPostById(Long postId) {
        return userPostDao.countUserPostById(postId);
    }

    /**
     * 删除岗位信息
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deletePostById(Long postId) {
        postDao.deleteById(postId);
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 批量删除岗位信息
     *
     * @param postIds 需要删除的岗位ID
     * @return 结果
     * @throws Exception 异常
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    @Override
    public int deletePostByIds(Long[] postIds) {
        for (Long postId : postIds) {
            SysPost post = selectPostById(postId);
            if (countUserPostById(postId) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
        postDao.deleteByPostIdIn(Arrays.asList(postIds));
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 新增保存岗位信息
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertPost(SysPost post) {
        post.setCreateTime(new Date());
        postDao.save(post);
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 修改保存岗位信息
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updatePost(SysPost post) {
        postDao.save(post);
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }
}
